using Quartz;
using RCS.Config;



public static class ServiceCollectionQuartzConfiguratorExtensions
{
    public static void AddJobAndTrigger<T>(this IServiceCollectionQuartzConfigurator quartz, IConfiguration configuration) where T : IJob
    {
        string jobName = typeof(T).Name;
        var options = GetCronJobOptions(configuration, jobName);
        
        var jobKey = new JobKey(jobName);
        quartz.AddJob<T>(opts => opts.WithIdentity(jobKey));
        quartz.AddTrigger(opts => opts
            .ForJob(jobKey)
            .WithIdentity(jobName + "-trigger")
            .WithCronSchedule(options.Schedule!));
    }


    private static GenericCronJobOptions GetCronJobOptions(IConfiguration configuration, string jobName)
    {
        var configKey = $"Quartz:{jobName}";
        var configurationSection = configuration.GetSection(configKey);
        var options = new GenericCronJobOptions();
        configurationSection.Bind(options);

        if (string.IsNullOrEmpty(options.Schedule))
        {
            throw new ConfigurationException($"No Cron schedule found for job '{jobName}' in configuration at '{configKey}'");
        }

        return options;
    }
}

public class ConfigurationException : Exception
{
    public ConfigurationException(string message) : base(message) { }
}

